
#include <stdint.h>
#include <string.h>
#include <ICC/Connector.h>
#include <ICC/Slot.h>

#include "exception.h"
#include "utils.h"
#include "asn1.h"
#include "tlv.h"
#include "dispatcher.h"
#include "ipcMessage.h"
#include "command.h"
#include "HIDRF.h"
#include "SIM.h"
#include <debug.h>

int HID_SAM_QueryECP(uint32_t* tb_tci, uint8_t* expr_tra){
	uint8_t atr[32];
	uint8_t alen;
	int ret;
#if 0
	int ret = SIM_PowerOn(atr, &alen);
	if(ret){
		LOG_I("PowerOn Fail(%d)", ret);
		return ret;
	}
#endif 
	uint8_t *resp;
	uint16_t rlen = 0;
	ret = SamCommand_QueryECP(&resp, &rlen);
	if(ret){
		LOG_I("HID_SAM_QueryECP Fail(%d)", ret);
		return ret;
	}
	//提取 TB/TCI
	uint8_t data[16];
	uint8_t len;
	uint8_t tag = ASN1_CHOICE_PRIMITIVE|0;
	ret = SamCommand_ExtractData(resp, rlen, tag, data, &len);
	if(ret){
		LOG_E("HID_SAM_QueryECP tb_tci: %d", ret);
		return ret;
	}
	if(len != 4){
		LOG_E("tb_tci (len = %d)", len);
		return -1;
	}
	memcpy(tb_tci, data, len);
	LOG_B("tb_tci", data, len, 16);
	//提取 EXPRESS/TRA
	tag = ASN1_CHOICE_PRIMITIVE|1;
	ret = SamCommand_ExtractData(resp, rlen, tag, data, &len);
	if(ret){
		LOG_E("HID_SAM_QueryECP: %d", ret);
		return ret;
	}
	if(len != 1){
		LOG_E("expr_tra (len=%d)", ret);
		return -2;
	}
	*expr_tra = data[0];
	LOG_I("expr_tra: %02X", data[0]);
	return 0;
}


